package poswar.contribute.mbean;

import java.util.LinkedList;

import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import org.apache.log4j.Logger;

import poswar.contribute.dao.BoardDao;
import poswar.contribute.model.Board;
import poswar.contribute.model.Post;



@ManagedBean
@ApplicationScoped
public class BoardBean {
	private static final Logger logger = Logger.getLogger(BoardBean.class);

	private Board board;
	
	private Object mutex = new Object();
	
	private BoardDao boardDao;
		
	@PostConstruct
	private void init() {
		boardDao = new BoardDao();
		board = boardDao.load();
	}
	
	public void clean() {
		synchronized(mutex) {
			board.getPosts().clear();
		}
	}

	public LinkedList<Post> getPosts() {
		synchronized(mutex) {
			LinkedList<Post> copy = new LinkedList<Post>();
			copy.addAll(board.getPosts());
			return copy;
		}
	}

	public void post(Post post) {
		synchronized(mutex) {
			logger.debug(post.getEmail() + "\t" + post.getContents());
			board.getPosts().addFirst(post);
			
			boardDao.save(board);
		}		
	}	
}
